package cn.exrick.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import cn.exrick.common.exception.XmallException;
import cn.exrick.controller.SMSController;
import cn.exrick.mapper.TbMemberMapper;
import cn.exrick.pojo.TbMember;
import cn.exrick.pojo.TbMemberExample;
import cn.exrick.service.LoginService;
import cn.exrick.service.RegisterService;
import cn.exrick.utils.enums.MemberCertifyEnum;
import cn.exrick.utils.enums.MemberVipEnum;
import io.rong.RongCloud;
import io.rong.models.response.TokenResult;
import io.rong.models.user.UserModel;


@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private TbMemberMapper tbMemberMapper;
    @Autowired
    private LoginService loginService;

    @Value("${rongcloud.appKey}")
    private String appKey;
    @Value("${rongcloud.appSecret}")
    private String appSecret;

    @Override
    public boolean checkData(String param, int type) {

        TbMemberExample example = new TbMemberExample();
        TbMemberExample.Criteria criteria = example.createCriteria();
        criteria.andStateEqualTo(1);
        //1：用户名 2：手机号 3：邮箱
        if (type == 1) {
            criteria.andUsernameEqualTo(param);
        } else if (type == 2) {
            criteria.andPhoneEqualTo(param);
        } else if (type == 3) {
            criteria.andEmailEqualTo(param);
        } else {
            return false;
        }

        List<TbMember> list = tbMemberMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return false;
        }
        return true;
    }

    @Override
    public int register(String phone, String userName, String userPwd, String code, String city) {

        TbMember tbMember = new TbMember();
        tbMember.setUsername(userName);
        tbMember.setPhone(phone);
        if (phone == null || userName == null || userPwd == null || userName.isEmpty() || userPwd.isEmpty() || phone.isEmpty()) {
            return -1; //用户名密码不能为空
        }

        if (!SMSController.checkCode(phone, code)) {
            throw new XmallException("验证码错误");
        }

        if (!checkData(phone, 2)) {
            throw new XmallException("手机号已被注册");
        }

        //MD5加密
        String md5Pass = DigestUtils.md5DigestAsHex(userPwd.getBytes());
        tbMember.setPassword(md5Pass);
        tbMember.setState(1);
        tbMember.setCreated(new Date());
        tbMember.setUpdated(new Date());
        tbMember.setCity(city);
        tbMember.setCertify(MemberCertifyEnum.CERTIFYFAIL.getId());
        tbMember.setVip(MemberVipEnum.NOTVIP.getId());
        long id = tbMemberMapper.insert(tbMember);
        if (id != 1) {
            throw new XmallException("注册用户失败");
        }
        tbMember = loginService.findByPhone(phone);
        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        UserModel userModel = new UserModel();
        userModel.setId(tbMember.getId().toString());
        userModel.setName(tbMember.getUsername());
        userModel.setPortrait(StringUtils.isEmpty(tbMember.getFile()) ? "/empty" : tbMember.getFile());
        try {
            TokenResult userGetTokenResult = rongCloud.user.register(userModel);
            if (userGetTokenResult.getCode() == 200) {
                tbMember.setRongCloud(userGetTokenResult.getToken());
                tbMemberMapper.updateByPrimaryKey(tbMember);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }


}
